package com.arvato.wxwork.controller.front.login;


import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.arvato.minipro.bean.bean_dto.common.Query;
import com.arvato.minipro.bean.bean_dto.common.Result;
import com.arvato.common.config_bean.WxworkConfig;
import com.arvato.common.https.WxworkMiniproOwnRequestUtil;
import com.arvato.common.redis.RedisUtil;
import com.arvato.common.util.ContantFinalUtil;
import com.arvato.common.util.JsonUtil;
import com.arvato.common.util.MD5Util;
import com.arvato.wxwork.bean.bean_do.staff.WxworkStaffInfoDo;
import com.arvato.wxwork.bean.bean_vo.staff.WxworkStaffInfoVo;
import com.arvato.wxwork.service.staff.WxworkStaffInfoService;

/**
 * 小程序在企业微信环境下的登录获取userid 
 * @author ZHAN655
 *
 */
@RestController
@RequestMapping("/wxwork/minipro")
public class WxworkMiniproAuthController{
	
	@Autowired
	private RedisUtil redisUtil;
	
	@Autowired
	private JsonUtil jsonUtil;

	@Autowired
	private WxworkMiniproOwnRequestUtil wxworkMiniproOwnRequestUtil;

	private Logger logger = LoggerFactory.getLogger(WxworkMiniproAuthController.class);

	@Autowired
	private WxworkStaffInfoService wxworkStaffInfoService;
	
	@ResponseBody
	@RequestMapping(value="/access_token")
	public Result getVerifyTicket(HttpServletRequest req) {
		// 获取小程序的access_token
		String token = wxworkMiniproOwnRequestUtil.getMiniproAccessToken();
		if(token == null) {
			return Result.fail("获取token失败");
		}
		return Result.success(token);
	}
	
	/**
	 * 企业微信登录
	 * @param req
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/login")
	public Result wxworkLogin(HttpServletRequest req, HttpServletResponse resp, String code, String brand) {
		// 因为要兼容三个品牌使用 所以登录的时候携带品牌参数 brand
		if(!ContantFinalUtil.BRAND_NAME_LIST.contains(brand.toUpperCase())) {
			return Result.fail("无效品牌登录名");
		}
		// 首先获取小程序的accessToken
		String accessToken = wxworkMiniproOwnRequestUtil.getMiniproAccessToken();
		if(accessToken == null) {
			return Result.fail("获取access_token失败,请稍后再试。");
		}
		Map<String, Object> resultMap = wxworkMiniproOwnRequestUtil.login(code, accessToken);
		// 当微信给的返回值errcode == 0时候，用户登录成功
		if(!"0".equals(resultMap.get("errcode") + "")) {
			logger.info("用户登录失败，请稍后再试或者联系管理员。错误代码：" + resultMap.get("errcode"));
			return Result.fail(resultMap);
		}
		String userid = resultMap.get("userid") + "";
		// 根据userid，查询用户的信息
		WxworkStaffInfoDo staffInfoDo = wxworkStaffInfoService.getRemoteStaffInfo(userid);
		staffInfoDo.setUserid(userid);
		staffInfoDo.setCorpid(WxworkConfig.CORPID);
		staffInfoDo.setCreateTime(new Date());
		staffInfoDo.setBrand(brand);
		staffInfoDo.setCreateUser("system");
		staffInfoDo.setUpdateTime(new Date());
		staffInfoDo.setUpdateUser("system");
		// 查看本地库有没有当前用户 有则更新 没有则插入
		Query query = new Query();
		query.put("userid", userid);
		query.put("brand", brand);
		query.put("status", "1");
		List<WxworkStaffInfoVo> listStaffInfo = wxworkStaffInfoService.listStaffByQuery(query);
		try {
			if(listStaffInfo.size() >= 1) {
				staffInfoDo.setStaffId(listStaffInfo.get(0).getStaffId());
				staffInfoDo.setName(null);
				wxworkStaffInfoService.update(staffInfoDo);
			}else {
				staffInfoDo.setStatus(1);
				wxworkStaffInfoService.insert(staffInfoDo);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		WxworkStaffInfoVo staffVo = wxworkStaffInfoService.getStaffById(staffInfoDo.getStaffId());
		// 登录成功之后 将用户信息存储在redis里面 用户的id为key 详情为value
		String key = MD5Util.md5(staffInfoDo.getStaffId());
		redisUtil.set(key, jsonUtil.obj2String(staffVo), 7200);
		// 小程序没有cookie 就返给小程序一个token
		staffVo.setToken(key);
		return Result.success(staffVo);
	}
	
}
